package social.p2p.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.jxta.discovery.DiscoveryEvent;
import net.jxta.discovery.DiscoveryListener;
import net.jxta.discovery.DiscoveryService;
import net.jxta.document.Advertisement;
import net.jxta.document.AdvertisementFactory;
import net.jxta.document.Element;
import net.jxta.protocol.PipeAdvertisement;
import social.p2p.model.Foto;
import social.p2p.model.FotoAdvertisement;
import social.p2p.model.NodoFotoAdvertisement;
import social.p2pnative.AdvertisementFactoryGen;
import social.p2pnative.PartialImplAdvertisement;

/**
 *
 * @author cadmilo
 */
public class AdvertisementManager implements DiscoveryListener {

    private DiscoveryService discovery;
    private static AdvertisementFactoryGen afg;
    private PipeAdvertisement pAdv;
    private Socialp2pController controller;

    static {
        try {
            afg = (AdvertisementFactoryGen) Class.forName("social.p2pnative.AdvertisementFactoryGenImpl").newInstance();
        } catch (Exception ex) {
            Logger.getLogger(AdvertisementManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public AdvertisementManager(DiscoveryService discovery, PipeAdvertisement pAdv, Socialp2pController controller) {
        this.discovery = discovery;
        this.pAdv = pAdv;
        this.controller = controller;
        discovery.addDiscoveryListener(this);
    }

    public void publishPhotoAdvertisement(Foto photo) throws IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
        FotoAdvertisement adv = (FotoAdvertisement) afg.getInstance(FotoAdvertisement.class);
        adv.setAlto(photo.getAlto() + "");
        adv.setAncho(photo.getAncho() + "");
        adv.setDescargada(photo.isDescargada() + "");
        adv.setId(photo.getId());
        adv.setUserId(photo.getUserId());
        adv.setPersonas(photo.getPersonas());
        adv.setPipeAdv(pAdv);
        adv.setTags(photo.getTags());
        adv.setTamanio(photo.getTamanio().intValue() + "");
        adv.setTipo(photo.getTipo());
        adv.setAfinidad(photo.getAfinidad());
        if (photo.getTiempoDescarga() != null) {
            adv.setTiempoDescarga(sdf.format(photo.getTiempoDescarga()));
        }
        if (photo.getTiempoRegistro() != null) {
            adv.setTiempoRegistro(sdf.format(photo.getTiempoRegistro()));
        }
        adv.setUtcDescarga(photo.getUtcDescarga() + "");
        adv.setUtcRegistro(photo.getUtcRegistro() + "");
        discovery.publish(adv);
    }
    
    public void publisNodoAdvertisement(String nombre, String fecha) throws IOException {
        NodoFotoAdvertisement adv = (NodoFotoAdvertisement) afg.getInstance(NodoFotoAdvertisement.class);
        adv.setName(nombre);
        adv.setConnectionTime(fecha);
        adv.setPipeAdv(pAdv);
        discovery.publish(adv);
    }

    public static Foto getFoto(FotoAdvertisement adv) {
        Foto f = new Foto();
        f.setId(adv.getId());
        f.setUserId(adv.getUserId());
        f.setDescargada(Boolean.valueOf(adv.getDescargada()));
        f.setAlto(new Integer(adv.getAlto()));
        f.setAncho(new Integer(adv.getAncho()));
        f.setPersonas(adv.getPersonas());
        f.setTags(adv.getTags());
        f.setAfinidad(adv.getAfinidad());
        f.setTamanio(Double.parseDouble(adv.getTamanio()));
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
        try {
            f.setTiempoRegistro(sdf.parse(adv.getTiempoRegistro()));
        } catch (Exception ex) {
        }
        try {
            f.setTiempoDescarga(sdf.parse(adv.getTiempoDescarga()));
        } catch (Exception ex) {
        }
        if (!adv.getUtcDescarga().equals("null")) {
            f.setUtcDescarga(new Integer(adv.getUtcDescarga()));
        }
        f.setUtcRegistro(new Integer(adv.getUtcRegistro()));
        return f;
    }

    @Override
    public void discoveryEvent(DiscoveryEvent de) {
        System.out.println("algo paso");
    }

    public static AdvertisementFactory.Instantiator getInitiator(final Class<? extends PartialImplAdvertisement> clazz) {
        return afg.getInitiator(clazz);
    }

    public void searchPhotoAdvertisement(String field, String searchText) {
        if (field.equals("personas")) {
            searchText = "*" + searchText + "*";
        }
        discovery.getRemoteAdvertisements(null, DiscoveryService.ADV, field, searchText, 10, new DiscoveryListener() {

            @Override
            public void discoveryEvent(DiscoveryEvent de) {
                System.out.println("---------Recuperando Respuesta busqueda-----");
                ArrayList<FotoAdvertisement> resp = new ArrayList<FotoAdvertisement>();
                Enumeration<Advertisement> result = de.getSearchResults();
                while (result.hasMoreElements()) {
                    Advertisement advertisement = result.nextElement();
                    if (advertisement.getAdvType().equals(FotoAdvertisement.getAdvertisementType())) {
                        resp.add((FotoAdvertisement) advertisement);
                    }
                }
                controller.searchPhotoResult(resp, de.getQueryID());
            }
        });
    }

    void searchPhotoAffinityAdvertisement(String af) {
        discovery.getRemoteAdvertisements(null, DiscoveryService.ADV, "afinidad", af, 10, new DiscoveryListener() {

            @Override
            public void discoveryEvent(DiscoveryEvent de) {
                System.out.println("---------Recuperando Respuesta busqueda afinidad-----");
                ArrayList<FotoAdvertisement> resp = new ArrayList<FotoAdvertisement>();
                Enumeration<Advertisement> result = de.getSearchResults();
                while (result.hasMoreElements()) {
                    Advertisement advertisement = result.nextElement();
                    if (advertisement.getAdvType().equals(FotoAdvertisement.getAdvertisementType())) {
                        resp.add((FotoAdvertisement) advertisement);
                    }
                }
                controller.searchAffinityPhotoResult(resp, de.getQueryID());
            }
        });
    }

    void searchNodes() {
        discovery.getRemoteAdvertisements(null, DiscoveryService.ADV, "name", "*", 10, new DiscoveryListener() {

            @Override
            public void discoveryEvent(DiscoveryEvent de) {
                System.out.println("---------Recuperando Respuesta busqueda-----");
                ArrayList<NodoFotoAdvertisement> resp = new ArrayList<NodoFotoAdvertisement>();
                Enumeration<Advertisement> result = de.getSearchResults();
                while (result.hasMoreElements()) {
                    Advertisement advertisement = result.nextElement();
                    if (advertisement.getAdvType().equals(NodoFotoAdvertisement.getAdvertisementType())) {
                        resp.add((NodoFotoAdvertisement) advertisement);
                    }
                }
                controller.searchForOtherNodesResult(resp);
            }
        });
    }

    
}
